package com.hermit.qmst.UI.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.hermit.qmst.MainActivity;
import com.hermit.qmst.R;
import com.hermit.qmst.request.DownLoadMusic;
import com.hermit.qmst.request.RequestTaskInterface;
import com.hermit.qmst.request.UpdateProcessInterface;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.Log;
import com.hermit.qmst.tools.ParseXML;
import com.hermit.qmst.tools.Preferences;
import com.hermit.qmst.tools.Utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by hermithermit on 15/2/16.
 */
public class LoginActivity extends Activity implements View.OnClickListener {

    private String mPhone;
    private String mPassword;

    private EditText metPhone;
    private EditText metPassword;
    private Button mbtnLogin;
    private ProgressDialog mProgressDialog;
    private static LoginActivity mInstance;
    private String TAG = "LoginActivity";

    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mInstance = this;
        mHandler = new Handler();
        initView();
    }

    public static LoginActivity getInstance() {
        return mInstance;
    }

    private void initView() {
        metPhone = (EditText) findViewById(R.id.et_login_phone);
        metPassword = (EditText) findViewById(R.id.et_login_pwd);
        mbtnLogin = (Button) findViewById(R.id.bt_login);
        mbtnLogin.setOnClickListener(this);
        Preferences preferences = new Preferences(this);
        Common.isShowRegister = preferences.getPreferenceBooleanValue("isShowRegister");
        if (Common.isShowRegister) {
            findViewById(R.id.tv_register).setOnClickListener(this);
            findViewById(R.id.tv_register).setVisibility(View.VISIBLE);
        }
    }

    private void request_login() {
        mProgressDialog = ProgressDialog.show(this, "提示", "系统正在处理，请稍后…", false, false);
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = "";
        try {
//            http://120.76.191.63/szdh/userlogin.php?regnum=13309012777&regpwd=123456&acct=%E5%85%A8%E6%B0%91%E5%95%86%E9%80%9A
            url = Common.submitLoginPath() + "regnum=" + mPhone + "&regpwd=" + mPassword + "&acct=" + URLEncoder.encode(Common.mAgentName, "utf-8");
        } catch (UnsupportedEncodingException e) {

        }
        Log.i("LoginActivity+url：", url, true);
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String s) {
                Log.i("LoginActivity", s, true);
                if (s != null && s.length() > 0) {

                    String code = ParseXML.parseResponseXML(s, "Ret");
                    Log.i(TAG, "submitQueryPicPath = " + code, true);
                    if (code.equals("0")) {
                        Preferences p = new Preferences(LoginActivity.this);
                        p.setPreferenceStringValue(Preferences.MY_PHONE, mPhone);
                        p.setPreferenceStringValue(Preferences.MY_PASSWORD, mPassword);

                        //直拨账号
                        String acctName = ParseXML.parseResponseXML(s, "AcctName");
                        p.setPreferenceStringValue(Preferences.SIP_ACCOUNT, acctName);
                        String agent = ParseXML.parseResponseXML(s, "Agent_id");
                        Common.mAgentId = agent;
                        p.setPreferenceStringValue(Preferences.SIP_AGENT, agent);

                        final String agent_id_third = ParseXML.parseResponseXML(s, "agent_id_third");
                        p.setPreferenceStringValue(Preferences.SIP_AGENT_THIRD, agent_id_third);
                        String userId = ParseXML.parseResponseXML(s, "id");
                        p.setPreferenceStringValue(Preferences.USER_ID, userId);
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        LoginActivity.this.finish();

                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                getMusic();
                            }
                        }, 1000);
                    } else if (code.equals("1")) {
                        Toast.makeText(LoginActivity.this, "此用户未注册", Toast.LENGTH_LONG).show();
                    } else if (code.equals("2")) {
                        Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_LONG).show();
                    } else if (code.equals("8")) {
                        Toast.makeText(LoginActivity.this, "此账号在其他代理商登录", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(LoginActivity.this, "未知错误", Toast.LENGTH_LONG).show();
                    }
                    mProgressDialog.dismiss();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.i("LoginActivity", "错误 = " + volleyError.getLocalizedMessage(), true);
                Toast.makeText(LoginActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                mProgressDialog.dismiss();
            }
        });


        requestQueue.add(request);


    }

    private void getMusic() {
        DownLoadMusic downLoadMusic = new DownLoadMusic(new RequestTaskInterface() {
            @Override
            public void postExecute(String paramString) {

            }
        }, Common.getMusic() + Common.mAgentId, new UpdateProcessInterface() {
            @Override
            public void processUpate(int value) {

            }
        }, this);
        downLoadMusic.execute();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.bt_login:
                mPhone = metPhone.getText().toString().trim();
                mPassword = metPassword.getText().toString().trim();
                if (!Utils.isMobileNO(mPhone)) {
                    Toast.makeText(LoginActivity.this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (mPassword.length() < 6) {
                    Toast.makeText(LoginActivity.this, "密码至少设置6位", Toast.LENGTH_SHORT).show();
                    return;
                }
                request_login();
                break;
            case R.id.tv_register:
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }

    }
}
